import React from 'react';
import Login from './login';
import {Button } from 'antd';
import * as conf from './config';
import './style.less';

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      isLogin: localStorage.getItem('isLogin')
    };
  }

  handleSubmit = () => {
    if(this.onChange()){
      conf.request({
        url:conf.api.rbac.login,
        data:{
          name:$('#name').val(),
          password:$('#password').val()
        }
      }).then(result=>{
        //console.log(result);
        if(result.errno === 0){
          localStorage.setItem('token',result.data);
          localStorage.setItem('isLogin','true');
          this.setState({isLogin:'true'});
        }else{
          conf.tips(result);
        }
      });
    }
  };


  onChange=()=>{
    let obj = $('#login');
    let state = true;
    obj.find('input[data-required="true"]').each(function(){
      if($(this).val() === ''){
        $(this).addClass('bred');
        state = false;
      }else{
        $(this).removeClass('bred');
      }
    });
    return state
  };

  render() {
    if(this.state.isLogin === 'true'){
      return (
        <div id="layout" style={{height:'100%'}}>
          {this.props.children}
        </div>
      )
    }else{
      return (
        <Login>
          <Button type="primary" htmlType="submit" className="loginButton" onClick={this.handleSubmit}>
            登录
          </Button>
        </Login>
      )
    }
  }
}


export default App;